package com.questetra.bpms.android;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

public class WorkitemAdapter extends ArrayAdapter<Workitem> {
    private LayoutInflater inflater;

    private int textViewResourceId;

    private List<Workitem> workitems;

    public WorkitemAdapter(Context context, int textViewResourceId,
                           List<Workitem> workitems) {
        super(context, textViewResourceId, workitems);

        this.textViewResourceId = textViewResourceId;
        this.workitems = workitems;

        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView != null) {
            view = convertView;
        } else {
            view = inflater.inflate(textViewResourceId, null);
        }

        final Workitem workitem = workitems.get(position);

        Button button = (Button) view.findViewWithTag("button");
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                Uri uri = Uri.parse(OAuthService.getInstance().getQbpmsUrl()
                        + "/SP/PE/Workitem/Form/view?workitemId="
                        + workitem.getId().longValue());
                Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                getContext().startActivity(intent);
            }
        });
        TextView textView = (TextView) view.findViewWithTag("processModel");
        textView.setText(workitem.getProcessModelInfoName());
        textView = (TextView) view.findViewWithTag("title");
        textView.setText(workitem.getTitle());

        return view;
    }
}
